//
//  RMAppDelegate.m
//  rmplanner
//
//  Created by Andrew Pigram on 2/05/12.
//  Copyright (c) 2012 PiAMP Productions. All rights reserved.
//

#import "RMAppDelegate.h"
#import "RMDetailViewController.h"
#import "RMParser.h"

@implementation RMAppDelegate

@synthesize window = _window, uid, retData;

#pragma mark UIApplication launching functions

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
	// Always nullify the application icon badge
	application.applicationIconBadgeNumber = 0;
	
	if ([launchOptions valueForKey:UIApplicationLaunchOptionsRemoteNotificationKey])
	{
		// load the detail view controller and supply it data parsed from a special XML file
		UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Response" message:[[[launchOptions valueForKey:UIApplicationLaunchOptionsRemoteNotificationKey] valueForKey:@"aps"] valueForKey:@"alert"] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alert show];
	}
    return YES;
}
							
- (void)applicationWillResignActive:(UIApplication *)application
{
	// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
	// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
	// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
	// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
	// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
	// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
	application.applicationIconBadgeNumber = 0;
}

- (void)applicationWillTerminate:(UIApplication *)application
{
	// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark Push notification delegate functions

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    // create the url containing the device token as a PHP argument
    NSString* host = @"rmplanner.net";
    
    // parse the device token
    NSString* urlString = @"/kitchen/scripts/addDevice"; // change to reflect the actual URL
    NSURL* url = [[NSURL alloc] initWithScheme:@"http" host:host path:urlString];
    
    // create the request and send it synchronously using POST
    NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];
	[request setHTTPMethod:@"POST"];
	
	NSString* devToken = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
	devToken = [devToken stringByReplacingOccurrencesOfString:@" " withString:@""];
	
	[[NSUserDefaults standardUserDefaults] setValue:devToken forKey:@"devToken"];
	
	// create a POST string with the device token and the user ID, and attach it to the HTTP body
	NSData* tokenData = [[NSString stringWithFormat:@"devtoken=%@&uid=%d&device=iOS&notifiable=%d", devToken, [[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"] intValue], YES] dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
	NSString* length = [NSString stringWithFormat:@"%d", [tokenData length]];
	[request setValue:length forHTTPHeaderField:@"Content-Length"];
	[request setHTTPBody:tokenData];
	
	// send the synchronous request
    NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	NSAssert((connection != nil), @"Could not connect");
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    // display an appropriate error message
    NSLog(@"Failed to register for push notifications: %@", [error userInfo]);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
	// nullify the application icon badge
	application.applicationIconBadgeNumber = 0;
	
	// display the response in an alert view
	UIAlertView* feedbackAlert = [[UIAlertView alloc] initWithTitle:@"Response" message:[[userInfo valueForKey:@"userInfo"] valueForKey:@"content"] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
	[feedbackAlert show];
}

#pragma mark NSURLConnection delegate functions

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    // display an appropriate error message
	NSLog(@"Connection failed: %@", [error userInfo]);
	connection = nil;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
	// initialise the data container
	retData = [NSMutableData data];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	// append the downloaded data to the data container
	[retData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	// log the downloaded response
	connection = nil;
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	NSLog(@"%@", [[NSString alloc] initWithData:retData encoding:NSUTF8StringEncoding]);
}

@end
